package org.bbs.demo.user.api;

import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.advice.SysException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.user.dao.UploadAvatarDao;
import org.bbs.demo.user.dto.AvatarDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

@RestController
@RequestMapping("/user/avatar")
@Transactional
public class UploadAvatarApi {

    @Autowired
    public UploadAvatarDao uploadAvatarDao;


    @PostMapping("/upload")
    public Result uploadAvatar(MultipartFile avatar, @RequestHeader(BBSConstants.HEADER_PARAM_TOKEN) String token) throws IOException {

        // 通过流获取图片
        String filename = UUID.randomUUID().toString().concat(".jpg"); //.replace("-", "");

        InputStream in = avatar.getInputStream();
        OutputStream out = new FileOutputStream(BBSConstants.UPLOAD_DIR + "/" + filename);

        byte[] buffer = new byte[1024 * 1024];
        int len = -1;

        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }

        out.flush();
        out.close();
        in.close();


        // 更新数据库的相应内容
        int updateFlag = 0;
        AvatarDto avatarDto = new AvatarDto(JWTutil.getUserID(token), filename);

        try {
            updateFlag = uploadAvatarDao.avatarUpload(avatarDto);
        }
        catch (Exception e){
            throw new SysException("数据库update失败");
        }

        if (updateFlag == 1){
            return Result.OK("上传成功", filename);
        }
        else {
            throw new BusinessException("上传失败");
        }
    }

}
